package com.newture.lxz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.newture.lxz.controller.helper.Result;
import com.newture.lxz.db.mapper.*;
import com.newture.lxz.db.model.LdOrder;
import com.newture.lxz.db.model.LdOrderExample;
import com.newture.lxz.services.IDocumentsSrv;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/marketing")
@Validated

public class MarketingController {

    @Resource
    LdTagsMapper ldTagsMapper;
    @Resource
    LdTagRelationshipMapper ldTagRelationshipMapper;
    @Resource
    LdGoodsMapper ldGoodsMapper;
    @Resource
    LdWidgetMapper ldWidgetMapper;
    @Resource
    LdOrderMapper ldOrderMapper;
    @Autowired
    IDocumentsSrv iDocumentsSrv;
    @Resource
    CommonOrderSrv commonOrderSrv;


    Logger logger = LogManager.getLogger(DocumentController.class);

    @Autowired
    private MessageSource messageSource;


    ObjectMapper jacksonMapper = new ObjectMapper();

    @PostMapping("/createOrder")
    @ResponseBody
    public Result createOrder(@RequestParam(name = "formData", required = false) String formData) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        // json字符串转换为java对象
        HashMap<String, Object> paraJsonMap = mapper.readValue(formData, HashMap.class);
        String docType = (String) paraJsonMap.get("docType");
        String address = (String) paraJsonMap.get("address");
        String remark = (String) paraJsonMap.get("remark");

        ArrayList<HashMap<String, Object>> docs = (ArrayList<HashMap<String, Object>>) paraJsonMap.get("docs");

        ObjectMapper mapper2 = new ObjectMapper();
        String jsonParams = mapper2.writeValueAsString(paraJsonMap.get("params"));
        // json字符串转换为java对象

        List<Map<String, Object>> orderItems = new ArrayList<>();
        /* 遍历选择的文档，并计算总价 */
        for (int i = 0; i < docs.size(); i++) {
            /* 文档的商品id */
            String idStr = StringUtils.stripToEmpty((docs.get(i).get("id").toString()));
            long id = Long.valueOf(idStr);

            Map<String, Object> itemMap = new HashMap<>();

            itemMap.put("id", id);
            itemMap.put("specifications", jsonParams);

//            /* 商品折扣 */
//            String goodsDiscountIdStr = (String) docs.get(i).get("discountId");
//            String goodsDiscountVersionStr = (String) docs.get(i).get("discountVersion");
//            String goodsDiscountRelationVersionStr = (String) docs.get(i).get("discountRelationVersion");
//            String goodsDiscountRelationIdStr =(String) docs.get(i).get("discountRelationId");
//            if(StringUtils.isNotBlank(goodsDiscountIdStr) && StringUtils.isNotBlank(goodsDiscountVersionStr)
//                    && StringUtils.isNotBlank(goodsDiscountRelationVersionStr)
//                    && StringUtils.isNotBlank(goodsDiscountRelationIdStr)) {
//                itemMap.put("id", Long.parseLong(goodsDiscountIdStr));
//                itemMap.put("version", Integer.parseInt(goodsDiscountVersionStr));
//                itemMap.put("discountRelationId", Long.parseLong(goodsDiscountRelationIdStr));
//                itemMap.put("discountRelationVersion", Long.parseLong(goodsDiscountRelationVersionStr));
//            }

            orderItems.add(itemMap);
        }


        String orderSN = commonOrderSrv.createOrder(orderItems, docType, remark,
                address);

        LdOrder order = commonOrderSrv.findBySN(orderSN,
                new String[]{"customer_id", "sn", "status",
                        "total_price", "id", "version", "gmt_created"});

        return Result.success(order);
    }

    @PostMapping("/orderDetail")
    @ResponseBody
    public Result orderDetail(@RequestParam(name = "sn", required = false) String sn) throws JsonProcessingException {

        LdOrderExample widExam = new LdOrderExample();
        LdOrderExample.Criteria cr2 = widExam.createCriteria();
        cr2.andSnEqualTo(sn);
        widExam.setDynamicColumns(new String[]{"gmt_created","id","total_price","version"});
        List<LdOrder> fiOrder= ldOrderMapper.selectByExample(widExam);
        HashMap<String, Object> data = new HashMap<>();
        HashMap<String, Object> order = new HashMap<>();
        order.put("gmt_created", fiOrder.get(0).getGmtCreated());
        order.put("id", "");
        order.put("sn", sn);
        order.put("total_peice",fiOrder.get(0).getTotalPrice() );
        order.put("version",fiOrder.get(0).getVersion());
        data.put("order", order);
        HashMap<String, Object> orderDetailSnapshot = new HashMap<>();
        data.put("orderDetailSnapshot", orderDetailSnapshot);
        data.put("orderItemDiscount", "");
        HashMap<String, Object> orderItems = new HashMap<>();
        data.put("orderItems", orderItems);
        HashMap<String, Object> pay = new HashMap<>();
        data.put("pay", pay);
        data.put("priceDown", 0);
        data.put("totalPrice", fiOrder.get(0).getTotalPrice());



        return Result.success(data);

    }
}